package com.kaigejava.springwebsocket.controller.tomcatwebscoket;


import com.alibaba.fastjson.JSON;
import com.kaigejava.springwebsocket.utils.ChatUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * tommcat对websocket的支持
 */
@ServerEndpoint("/tomcatWebSocket/{userName}")
@Slf4j
public class TomcatWebSocket {

    @Autowired
    private ChatUserUtil chatUserUtil;
    /**
     * 打开连接后
      * @param session
     * @param userName
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) throws IOException {
        log.info("=== 打开连接了===");
        log.info("====session:{}", JSON.toJSONString(session));
        session.getBasicRemote().sendText("欢迎:"+userName+"访问系统");
        if( chatUserUtil.userSocketSessionMap.isEmpty() ){ //将当前登陆用户信息放到全局变量中
            chatUserUtil.userSocketSessionMap.put(userName,session);
        }else if(!chatUserUtil.userSocketSessionMap.containsKey("userName")){
            chatUserUtil.userSocketSessionMap.put(userName,session);
        }
    }

    /**
     * 关闭方法
     */
    @OnClose
    public void onClose(Session session ) throws IOException {
        log.info("断开连接。。。。。");
        //从当前登陆用户中清除离线用户
        removeUser(session);
    }

    /**
     * 从当前登陆用户中清除离线用户
     * @param session
     */
    private void removeUser(Session session) {
        log.info("===session:{}",JSON.toJSONString(session));
        Iterator<Map.Entry<String,Session>> it = chatUserUtil.userSocketSessionMap.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<String,Session> entry = it.next();
            log.info("===entry:{}",JSON.toJSONString(entry));
            if(entry.getValue().getId().equals(session.getId())){
                chatUserUtil.userSocketSessionMap.remove(entry.getKey());
            }

        }
    }

    @OnMessage
    public void onMessage(String message,Session session, @PathParam("userName") String userName) throws IOException {
        log.info("==接收到客户端发来的消息是:{}",message);
        if("凯哥Java".equals(message)){
            session.getBasicRemote().sendText("个人博客：www.kaigejava.com。微信公众号：凯哥Java(kaigejava)");
            session.getBasicRemote().sendText("欢迎一起学习");
        }else{
            session.getBasicRemote().sendText(message+"，系统已经收到....");
        }
       // session.getBasicRemote().sendText("您好:"+userName+" 您发送的消息"+message+"，系统已经收到....");
    }


    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        session.getBasicRemote().sendText("您好，系统发送了异常。。。。。");
        error.printStackTrace();
    }
}
